package server.db;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 获取数据库连接
 * @author skywalker
 *
 */
public final class DBUtil {
	
	private static Properties properties;
	private static final Logger logger = LogManager.getLogger("server.db.DbUtil");
	private static ComboPooledDataSource dataSource;

	private DBUtil() {}
	
	static {
		try {
			properties = new Properties();
			properties.load(DBUtil.class.getResourceAsStream("/c3p0.properties"));
			logger.info("c3p0配置文件加载成功");
			dataSource = new ComboPooledDataSource();
			dataSource.setDriverClass(properties.getProperty("c3p0.driverClass"));
			dataSource.setJdbcUrl(properties.getProperty("c3p0.url"));
			dataSource.setUser(properties.getProperty("c3p0.username"));
			dataSource.setPassword(properties.getProperty("c3p0.password"));
			dataSource.setMinPoolSize(Integer.parseInt(properties.getProperty("c3p0.minPoolSize")));
			dataSource.setMaxPoolSize(Integer.parseInt(properties.getProperty("c3p0.maxPoolSize")));
			logger.info("ComboPooledDataSource 初始化完成");
		} catch (IOException e) {
			logger.error("配置文件加载失败");
		} catch (PropertyVetoException e) {
			logger.error("c3p0配置名错误");
		}
	}
	
	/**
	 * 获取数据库连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}
	
	/**
	 * 关闭数据库连接
	 * @param connection 连接
	 */
	public static void close(Connection connection) {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 关闭数据库连接和Statement
	 * @param connection
	 * @param statement
	 */
	public static void close(Connection connection, Statement statement) {
		try {
			if (statement != null) {
				statement.close();
			}
			close(connection);
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 关闭数据库连接、Statement和ResultSet
	 * @param connection
	 * @param statement
	 */
	public static void close(Connection connection, Statement statement, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			close(connection, statement);
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
	}
	
}
